#!/usr/bin/python

import sys, subprocess

def cleanTok(tok):
  ts = tok.split(":")
  for i in xrange(len(ts)):
    t = ts[i].split(".")
    if len(t) > 1:
      ts[i] = t[0]
  desc = ts[0]+"".join([":"+ts[i+1] for i in xrange(len(ts)-1)])
  desc = desc.replace("n1", "n").replace("n2", "n").replace("p1", "m1").replace("p2", "m1").replace("p3", "m1")
  return desc

def getToken(line):
  line = line.replace("[","").replace("]","")
  toks = line.split(";")[0].split(",")
  if len(toks) > 3:
    return (",", ",", "interp")
  if toks[1] == "?":
    toks[1] = toks[0]
  if toks[2] == "?":
    toks[2] = "num"

  t = cleanTok(toks[2].split("|")[0])
  return (toks[0], toks[1], t)

if __name__ == "__main__":
  if len(sys.argv) != 3:
    print "morfeusz.py sourceFile destinationFile"
    sys.exit(-1)

  print "Morfeusz read "+sys.argv[1] 

  fSrc = open(sys.argv[1], "r")
  fDst = open(sys.argv[2], "w")

  fDst.write('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE cesAna SYSTEM "xcesAnaIPI.dtd">\n<cesAna xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" type="lex disamb">\n<chunkList>\n')

  process=subprocess.Popen(['morfeusz'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT);

  out = process.communicate( fSrc.read() )

  lines = out[0].split("\n")
  lastChar = None
  for l in lines:
    if len(l) > 1 and l[0] == "[":   
      tok = getToken(l)
      #fDst.write(str(tok))

      if tok[2] == "sp":
        continue
      
      if (lastChar == None or lastChar == ".") and tok[0][0].isupper():
         if lastChar != None:
           fDst.write('</chunk>\n')
         fDst.write('<chunk type="s">\n')
    
      fDst.write('<tok>\n')
      fDst.write('<orth>'+tok[0]+'</orth>\n')
      fDst.write('<lex disamb="1"><base>'+tok[1]+'</base><ctag>'+tok[2]+'</ctag></lex>\n')
      fDst.write('</tok>\n')

      lastChar = tok[0]
      
  fSrc.close()

  fDst.write("</chunk>\n</chunkList>\n</cesAna>\n")
  fDst.close()

  print "Morfeusz wrote "+sys.argv[2] 
